package com.tiancheng.trade.order.mq.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.tiancheng.trade.commom.core.data.MessageBody;
import com.tiancheng.trade.commom.core.enums.MessageTypeEnum;
import com.tiancheng.trade.commom.core.utils.MessageUtils;
import com.tiancheng.trade.commom.core.utils.ForestHttpUtil;
import com.tiancheng.trade.order.configuration.CallbackConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 回调工具类
 */
@Slf4j
@Component
public class CallbackUtil {

    @Resource
    private CallbackConfig callbackConfig ;

    /**
     * 推送信息到回调地址
     */
    public boolean callTarget(String targetUrl, MessageTypeEnum messageTypeEnum, Object data) {
        if (StringUtils.isEmpty(targetUrl) || Objects.isNull(messageTypeEnum) || Objects.isNull(data)) {
            log.error("推送回调消息异常，回调地址/消息类型/消息体为空！");
            return true;
        }
        final MessageBody msgData = this.getMsgData(messageTypeEnum.getCode(), data);
        Header[] headers = new BasicHeader[]{new BasicHeader("content-type", "application/json")};
        final String s = ForestHttpUtil.getInstance().doPostJson(targetUrl, msgData, headers);
        if (StringUtils.isEmpty(s)) {
            return false;
        }
        final JSONObject jsonObject = JSONObject.parseObject(s);
        log.info("回调业务系统返回：{}", jsonObject);
        return null != jsonObject && jsonObject.containsKey("ret") && jsonObject.getInteger("ret") == 0;
    }

    /**
     * 组织生成消息内容
     *
     * @param data
     * @return
     */
    private MessageBody getMsgData(String messageType, Object data) {
        return MessageUtils.sign(MessageUtils.getMsgData(messageType,data),callbackConfig.getSignKey());
    }

}
